/* main.js contains common functional js code, js code for navbar and js code for sidebar. */
window.EB_DEV = true; // if test local, set to true; otherwise (deployed onto server), set to false.

EB = {};
EB.util = {};

var login_form_return = false; // return from login form directly or redirect.
var dropdown_open = false; // indicates whether the dropdown-menu is open
var nav_msg_last = 0; // last check num of msg, default 0

$('document').ready(function() {
//    if (($.cookie('EB_REMEMBER_SESSION_IS_CHECKED') == null) || ($.cookie('EB_REMEMBER_SESSION_IS_CHECKED') == '0') ) {
//        check_login_status_and_call(check_cookies_and_login);
//    }
    
    if ($('#login_form').length > 0) {
        if ($('#login_modal').length > 0) {
            $('#login_modal').on('shown', function() {
                $('#login_email').focus();
            });
        } else {
            $('#login_email').focus();
        }
        $('#login_btn').click(function() {
            if($('#login_captcha').length > 0) {
                return verify_captcha(login_submit, function(){return false;});
            }
            else {
                return login_submit();
            }
        });
    }
    
    if ($('#find_pwd_set_form').length > 0) {
        $('#find_pwd_set_form').submit(function() {
            return find_pwd_set_submit();
        });
    }
    
    $('.eb-topnav .dropdown .nav_icon').hover(
        function() {
            if (!$(this).parent().hasClass('open')) {
                $(this).dropdown('toggle');            
            }
        }
    );
    $('.eb-topnav .dropdown .nav_icon ~ .dropdown-menu').hover(
        function() {
        },
        function(e) {
            $(this).prev('.nav_icon').dropdown('toggle');
        }
    );
    
    $('.nav_msg_div .close').click(function() {
        $('.nav_msg_div').hide('slow');
        $.post('msg/read_all');
    });
    $('.nav_msg_div a').click(function() {
        $('.nav_msg_div').hide('slow');    
        if (this.href == location.href) {
            location.reload();
        }
    });
    setInterval("any_msg()", 5000);
    
    $('.navbar-search input')
        .focusin(function() {
            $('#nav_search_btn').attr('class', 'icon-edit');
        })
        .focusout(function() {
            $('#nav_search_btn').attr('class', 'icon-search');
        });
    
    $('.eb-main-menu li').hover(function() { menu_hover($(this)); }, menu_hoverout);
    var $active = $('.eb-main-menu li.active');
    if ($active.length > 0) {
        menu_hover($active);
    } else {
        $('.eb-menu .nav_hover').hide();
    }
    
    /* jquery.placeholder */
    if ($.fn.placeholder != undefined) {
        $('input, textarea').placeholder();
    }
    /* img easing */
    
    /* trunc */
    if ($('[rel*=trunc-]').length > 0) {
        EB.util.trunc();
    }
    /* gototop */
    $(window).on('scroll', window, function(e) {
        if ($(window).scrollTop() > 800) {
            $('.top-top-btn').fadeIn('fast');
        } else {
            $('.top-top-btn').fadeOut('fast');
        }
    });
    $('.top-top-btn')
        .hover(
            function() {
				$(this).prev('.top_text').css('visibility', 'visible');
            }, 
            function() {
                $(this).prev('.top_text').css('visibility', 'hidden');
            }
        )
        .click(function() {
            $('html,body').animate({scrollTop:'0px'}, 'fast');
			$(this).prev('.top_text').css('visibility', 'hidden');
        });
    $('.top-fb-btn')
        .hover(
            function() {
				$(this).next('.top_text').css('visibility', 'visible');
            }, 
            function() {
                $(this).next('.top_text').css('visibility', 'hidden');
            }
        );
    
    $('#nav_msg_change_optional')
    	.click(
    		function() {
    			$.cookie('EB_SHOW_OPTIONAL_INFO_MSG', 'false', {path: '/'});
    			$('#nav_msg_optional_info').addClass('hide');
    			location.href = (window.EB_DEV ? "/ourplayground" : "") + "/profile/show_profile_form";
    		}
    	);
    
    if( $.cookie('EB_SHOW_OPTIONAL_INFO_MSG') != 'false' ) {
    	check_optional();
    }
});
function genSalt() {
    var chars = "0123456789abcdef".split('');
    var salt = "";
    for (var i = 0; i < 32; i++) {
        salt += chars[Math.floor(Math.random() * chars.length)];
    }
    return salt;
}
function encrypt(str) {
    return hex_md5(str);
}
function login_submit() {
    $.post("login/do_login", {
        email : $('#login_email').val(),
        password : encrypt($('#login_password').val()),
        remember : $('#login_remember').attr('checked') == 'checked'
    }, function(data, textStatus) {
        if (data.code == 1) {
            $('#login_modal').modal('hide');
            if (!login_form_return) {
                location.href = (window.EB_DEV ? "/ourplayground" : "") + "/mainpage";
            } else {
                login_form_return = false;
            }
        } else {
            $('#login_error')
                .text(data.html)
                .css('visibility', 'visible');
            $('div.control-group:has(#login_email)').addClass('error');
            $('div.control-group:has(#login_password)').addClass('error');
//临时禁用验证码
//            if( typeof( data.captchahtml ) !=  'undefined ') {
//                if( $('#login_captcha').length <= 0 )
//                $('div.control-group:has(#login_password)').after(data.captchahtml);
//            }
            
            $('#login_password').val('');
            $('#login_email').select();
        }
    }, "json");
    return false;
}

function verify_captcha(match_callback, unmatch_callback) {
    $.post("security/verify_captcha", {
        captcha: $('#login_captcha').val()
    }, function(data, textStatus) {
        if (data.match == 1) {
            $('#login_captcha_error').css('display', 'none');       
            $('div.control-group:has(#login_captcha)').removeClass('error');
            match_callback();
        } else {
            $('#login_captcha_error').css('display', 'block');
            $('div.control-group:has(#login_captcha)').addClass('error');
            
            $('#login_captcha').val('');
            $('#login_captcha').select();
            unmatch_callback();
        }
    }, "json");
    return false;
}

function find_pwd_set_submit() {
    var ifChecked = true;
    var reg_password = $('#reg_password').val();
    var reg_repassword = $('#reg_repassword').val();
    
    if (reg_password.length < 6) {    
        var $reg_password = $('#reg_password');
        $reg_password.nextAll('span').remove();
        $reg_password.after('<span class=\'help-inline\'>密码长度不得少于6位！</span>');
        $('div.control-group:has(#reg_password)').addClass('error');
        
        ifChecked = false;
        $reg_password.val('');
        $('#reg_repassword').val('');
    }
    
    if (reg_password !== reg_repassword) {
        var $reg_repassword = $('#reg_repassword');
        $reg_repassword.nextAll('span').remove();
        $reg_repassword.after('<span class=\'help-inline\'>密码输入不一致！</span>');
        $('div.control-group:has(#reg_repassword)').addClass('error');
        
        ifChecked = false;
        $('#reg_password').val('');
        $reg_repassword.val('');
    }
    
    if ( ifChecked ) {
        var salt = genSalt();
        var pw_encrypt = encrypt(encrypt(reg_password) + salt);
        
        $('#reg_password').val(pw_encrypt + salt);
        return true;
    } else {
        return false;
    } 
}

// judge if the guest is login.
// if not, show the login modal first and then call callback after he log in.
function is_login(callback) {
    $.post("login/is_login", {
    }, function(data, textStatus) {
        if (data == false) {
            login_form_return = true;
            $('#login_modal')
                .on('hidden', function() {
                    is_login_check(callback);
                })
                .modal('show');
        } else {
            if (callback != undefined) {
                callback();
            }
        }
    });
    return false;
}
// double check if a guest log in. If he just close the modal, should do nothing.
function is_login_check(callback) {
    $.post("login/is_login", {
    }, function(data, textStatus) {
        if (data == false) {
            // do nothing
        } else {
            if (callback != undefined) {
                callback();
            }
        }
    });
    return false;
}

//// check the login status.
//// if not login, call the callback function.
//function check_login_status_and_call(callback) {
//    $.post("login/is_login", {
//    }, function(data, textStatus) {
//        if (data == false) {
//            if (($.cookie('EB_REMEMBER_SESSION_EMAIL') != null) &&
//                ($.cookie('EB_REMEMBER_SESSION_ID_TOKEN') != null) &&
//                ($.cookie('EB_REMEMBER_SESSION_SESS_TOKEN') != null) ) {
//                    callback();
//                }
//            else {
//                $.cookie('EB_REMEMBER_SESSION_IS_CHECKED', '1', { path: '/' });
//            }
//        }
//    });
//    return false;
//}
//
//// check the cookies and set a cookie to mark that the cookie has been checked
//function check_cookies_and_login() {
//    $.post("login/do_cookie_login", {
//    }, function(data){
//        if (data.code == 1) {
//            document.location.reload();
//        }
//    });    
//    $.cookie('EB_REMEMBER_SESSION_IS_CHECKED', '1', { path: '/' });
//    return false;
//}

function any_msg() {
    $.post('msg/any', {
    }, function(data) {
        if (data != 0) {
            if (nav_msg_last != data) {
                nav_msg_last = data;
                $('#nav_msg_part').removeClass('hide');
                $('.nav_msg_num').text(data);
                $('.nav_msg_div').show();
                $('.nav_msg_badge').show();
            }
        }
    }, 'text');
}

function check_optional() {
	$.post('msg/checkoptional', {
    }, function(data) {
        if (data == 0) {
        	$('#nav_msg_optional_info').removeClass('hide');
            $('.nav_msg_div').show();
            $('.nav_msg_badge').show();
        }
    }, 'text');
}

function menu_hover($me) {
    var $hover = $('.nav_hover');
        pos_me = $me.position().left;
    if ($hover.css('display') == 'none') {
        $hover.show();
    } else {
        $hover.stop(true);
    }
    $hover.animate({
        left: pos_me + 'px',
        width: $me.width()
    });
}
function menu_hoverout() {
    var $active = $('.eb-main-menu li.active');
    if ($active.length > 0) {
        var pos_active = $active.position().left;
        $('.nav_hover').animate({
            left: pos_active + 'px',
            width: $active.width()
        });
    } else {
        $('.nav_hover').hide();
    }
}

EB.util.trunc = function() {
    function get_real_length(str) {
        return str.replace(/[^\x00-\xff]/g, '**').length;
    }
    
    function get_trunc_str(str, len) {
        for (i = 0; i < str.length; i++) {
            len -= (str.charCodeAt(i) > 200) ? 2 : 1;
            if (len < 0) {
                return (str.substring(0, i) + '...');
            }
        }
        return str;
    }
    
    $('[rel*=trunc-]').each(function() {
        var content = $(this).attr('data-content');
        var len = get_real_length(content);
        var rel = $(this).attr('rel');
        var limit = parseInt(rel.substring(rel.lastIndexOf('-') + 1));
        if (len > limit) {
            $(this).text(get_trunc_str(content, limit));
            // hover
        } else {
            $(this).text(content);
        }
    });
};
EB.util.is_email = function(str) {
    var email_regex = /^[a-zA-Z0-9]([a-zA-Z0-9]*[-_.]?[a-zA-Z0-9]+)+@([\w-]+\.)+[a-zA-Z]{2,}$/;
    return email_regex.test(str);
}
EB.util.letter_modal = function(user_id, user_nickname) {
    var $modal = $('#letter_modal');
    if ($modal.length > 0) {
        //$('#letter_modal .letter_title').text('To: ' + user_nickname).attr('data-user-id', user_id);
        //$('#letter_modal #letter_content').val('');
        //$('#letter_modal #letter_res').removeClass();
        $modal.modal('show');
    } else {
        $.get('assets/templates/letter_modal.html', function(html) {
            $('body').append(html);
            $modal = $('#letter_modal');
            
            $modal.on('show', function() {
                $('#letter_modal .letter_title').text('To: ' + user_nickname).attr('data-user-id', user_id);
                $('#letter_modal #letter_content').val('');
                $('#letter_modal #letter_res').removeClass().addClass('hide');
            });
            $modal.modal('show');
        });
    }
}